package com.me.TextMissed_a1;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.CallLog;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	//private SharedPreferences preferences;
	//private final static String MY_PREFS = "TextMissed_a1";
	private Toast toast;
	private Timer timer;
	private TimerTask timerTask = new TimerTask() {
		@Override
		public void run() {
			Intent intent = new Intent(MyAppWidget.UPDATE_ONDEMAND);
			
			//get unread sms
			final Uri SMS_INBOX = Uri.parse("content://sms/inbox");        
	        Cursor unreadSMS = getContentResolver().query(SMS_INBOX, null, "read = 0", null, null);
	        int unreadMessagesCount = unreadSMS.getCount();
	        unreadSMS.deactivate();
	        
	        //get missed calls
	        Cursor cMissedCalls = getContentResolver().query(CallLog.Calls.CONTENT_URI, null,
	                CallLog.Calls.TYPE + "=?",
	                new String[] { String.valueOf(CallLog.Calls.MISSED_TYPE) },
	                null);
	        int missedCallsCount = cMissedCalls.getCount();
	        cMissedCalls.deactivate();
			
	        //intent.putExtra("WidgetText", "" + unreadMessagesCount);
	        intent.putExtra("WidgetTextSMS", "" + unreadMessagesCount);
			intent.putExtra("WidgetTextCALL", "" + missedCallsCount);
			sendBroadcast(intent);
			
			Log.d("_TextMissed_a1_", "TimerTask Unread SMS: "+unreadMessagesCount);
			Log.d("_TextMissed_a1_", "TimerTask Missed calls: "+missedCallsCount);
		}
	};

    @Override
    public void onCreate() 
    {
    	timer = new Timer();
		timer.scheduleAtFixedRate(timerTask, 5*1000, 10*1000);
		
    	Log.d("_TextMissed_a1_", "StartAtBootService Created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	Log.d("_TextMissed_a1_", "StartAtBootService -- onStartCommand()");
    	
    	// We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    	Log.d("_TextMissed_a1_", "StartAtBootService Destroyed");
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        Log.d("_TextMissed_a1_", "onStart");
        
        super.onStart(intent, startId);
        timer.scheduleAtFixedRate(timerTask, 5*1000, 10*1000);
    }
    
    //showToast
    public void showToast(String text) {
        toast.setText(text);
        toast.show();
    }

	public IBinder onBind(Intent intent) {
    	return null;
    }


}
